package com.sky.jtail.controller;


import cn.hutool.core.lang.UUID;
import com.sky.jtail.conf.AppConfig;
import com.sky.jtail.domain.*;
import com.sky.jtail.request.CloseRequest;
import com.sky.jtail.request.FilesRequest;
import com.sky.jtail.request.LoginRequest;
import com.sky.jtail.response.LoginResponse;
import com.sky.jtail.utils.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Controller
public class AppController {


    @Autowired
    private AppContainer appContainer;




    @Autowired
    private WebSocketContainer webSocketContainer ;


    @PostMapping("/resetPwd")
    @ResponseBody
    public LoginResponse resetPwd(LoginRequest loginRequest) {
        String initPassword = loginRequest.getInitPassword();
        String password = loginRequest.getPassword();
        if(StringUtils.isEmpty(initPassword) || StringUtils.isEmpty(password) ){
            return LoginResponse.builder().code(ResponseEnum.loginFailed.getCode()).msg(ResponseEnum.loginFailed.getText()).build();
        }

        if(AppConfig.password.equals(initPassword)){
            AppConfig.password = password ;
            AppConfig.resetPwdFlag= true;
            return LoginResponse.builder().code(ResponseEnum.resetPwdSuccess.getCode()).msg(ResponseEnum.resetPwdSuccess.getText()).build();

        }
        return LoginResponse.builder().code(ResponseEnum.wrongInitPwd.getCode()).msg(ResponseEnum.wrongInitPwd.getText()).build();
    }


    @PostMapping("/login")
    @ResponseBody
    public LoginResponse login(LoginRequest loginRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        String pwd = loginRequest.getPassword();
        if(StringUtils.isEmpty(pwd)){
            return LoginResponse.builder().code(ResponseEnum.needPwd.getCode()).msg(ResponseEnum.needPwd.getText()).build();
        }
        if(!AppConfig.resetPwdFlag){
            //尚未重置密码，先重置密码
            return LoginResponse.builder().code(ResponseEnum.needResetPwd.getCode()).msg(ResponseEnum.needResetPwd.getText()).build();

        }

        if(AppConfig.password.equals(pwd)){
            String authValue = UUID.fastUUID().toString();
            long loginTime = System.currentTimeMillis();

            httpServletRequest.getSession().setAttribute(AppConstant.webAuth,authValue);
            Cookie cookie = new Cookie(AppConstant.wsAuth, authValue);

            //将cookie对象加入response响应
            httpServletResponse.addCookie(cookie);
            appContainer.authValues.put(authValue,loginTime);
            return LoginResponse.builder().code(ResponseEnum.loginSuccess.getCode()).msg(ResponseEnum.loginSuccess.getText()).build();

        }
        return LoginResponse.builder().code(ResponseEnum.loginFailed.getCode()).msg(ResponseEnum.loginFailed.getText()).build();
    }



    @PostMapping("/files")
    @ResponseBody
    public List<FileObject> files(@RequestBody FilesRequest filesRequest,HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        String webAuth = (String) httpServletRequest.getSession().getAttribute(AppConstant.webAuth);

        List<FileObject> fileObjectList = new ArrayList<>();
        String dirPath = filesRequest.getPath();
        File file = new File(dirPath);
        if (!file.exists()) {
            return fileObjectList;
        }
        if (!FileUtil.isDir(dirPath)) {
            return fileObjectList;
        }
        fileObjectList = FileUtil.findFileList(file);

        FilesContainer filesContainer = new FilesContainer();

        fileObjectList.forEach(e -> filesContainer.put(e.getFileKey(),e));
        appContainer.userFiles.put(webAuth,filesContainer);


        Cookie cookie = new Cookie(AppConstant.favoriteDir, dirPath);

        //将cookie对象加入response响应
        httpServletResponse.addCookie(cookie);
        return fileObjectList;
    }

    @PostMapping("/closeLink")
    @ResponseBody
    public void closeLink(@RequestBody CloseRequest closeRequest) throws Exception {

        String filekey = closeRequest.getFileKey();
        WebSocketHandler ws = webSocketContainer.get(filekey);
        if(null != ws){
            ws.thread.interrupt();
            ws.inputStream.close();
            ws.isReader.close();
            ws.reader.close();
            ws.process.destroy();
        }






    }


}
